package com.chat.websocket.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

import com.chat.constant.tab.MessageConstant;
import com.chat.entity.TdChatGroup;
import com.chat.vo.back.BaseMessageVo;
import com.chat.websocket.online.OnlineManage;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 群聊业务
 * 
 * @author lwh
 *
 */
@Service
public class GroupChatService {

	/**
	 * 推送建群通知(ws)
	 * 
	 * @throws IOException
	 */
	public StringBuffer pushCreateGroupMsg(TdChatGroup group) throws IOException {
		// 离线用户栈
		StringBuffer leaveUsers = new StringBuffer();
		if (null != group.getGroupusers()) {
			String[] users = group.getGroupusers().split(",");
			for (int i = 0; i < users.length; i++) {
				// 把离线用户添加到离线用户栈
				if (false == OnlineManage.isOnlined(users[i])) {
					leaveUsers.append(users[i]);
					if (i != users.length - 1) {
						leaveUsers.append(",");
					}
				} else {
					Map<String, Object> body = new HashMap<String, Object>(0);
					BaseMessageVo<Map<String, Object>> msg = new BaseMessageVo<Map<String, Object>>();
					msg.setStatus("success");
					msg.setType(MessageConstant.Group);
					msg.setBody(body);
					msg.getBody().put("fromUser", group.getGroupadmin());
					msg.getBody().put("groupId", group.getGroupid());
					msg.getBody().put("createTime", group.getCreatetime());
					msg.getBody().put("msgType", MessageConstant.BodyType_Text);
					msg.getBody().put("message", "群创建时间为" + group.getCreatetime());
					TextMessage tmsg = new TextMessage(new ObjectMapper().writeValueAsString(msg));
					// 推送
					OnlineManage.getOnlineUser(users[i]).getSession().sendMessage(tmsg);
				}
			}
		}
		return leaveUsers;
	}

	/**
	 * 推送离线建群通知(ws)
	 */
	public void pushCreateGroupMsgLeave() {

	}

	/**
	 * 推送被修改的群信息(另处理离线用户)(群名称、群头像、群主)(ws)
	 */
	public void pushModifyGroupDetails() {

	}

	/**
	 * 推送离线被修改的群信息(群名称、群头像、群主)(ws)
	 */
	public void pushModifyGroupDetailsLeave() {

	}

	/**
	 * 推送群信息(ws)
	 */
	public void pushGroupMsg() {

	}

	/**
	 * 推送离线群信息(ws)
	 */
	public void pushGroupMsgLeave() {

	}

	/**
	 * 推送@信息
	 */
	public void pushAtGroupMsg() {

	}

	/**
	 * 推送离线@信息
	 */
	public void pushAtGroupMsgLeave() {

	}

	public void saveLeaveMsg() {

	}

}
